import http from "@src/config/http.ts"
import {getUserInfo} from "@src/utils/userInfo.ts"
import {template} from "@src/services/chatRoom.ts";
import backendUrlSet from "@src/config/backendUrlSet.ts";

const baseURL = "http://" + backendUrlSet

export interface userType {
    id?: number;
    name: string;
    email: string;
    avatar: string;
    gender: "male" | "female" | null;
    birthdate: string;
    isVisitor?: boolean;
}

export interface UserInfoType {
    token?: string
    user: userType
}

interface get_hall_info_data_type {
    data: {
        releaseRole: Array<number>
    }
}

export interface usersRegisterFromType {
    email: string;
    name: string;
    password: string;
    verificationCode: string;
    avatar: string;
}

export interface usersRegisterDataType {
    status: string,
    message: string,
    data?: {
        id: number;
    }
}

//登录返回类型
export interface usersLoginDataType {
    status: string;
    message: string;
    data: UserInfoType
}

//当前用户的关系 好友列表 返回类型
interface usersRelationshipsDataDataType {
    data: Array<usersRelationshipsDataType>
}

export interface usersRelationshipsDataType {
    "user_id": number;
    "friend_id": number;
    "relationship": string;
    "friend_name": string;
    "friend_avatar": string;
    "friend_email": string;
}

export interface templateType<T> {
    data: T;
}

export interface usersFriendRequestsDataType {
    "user_id": number;
    "friend_id": number;
    "relationship": string;
    "requester_name": string;
    "requester_avatar": string;
    "requester_email": string;
}


//https://binaryify.github.io/NeteaseCloudMusicApi/#/
interface ApiType {
    [key: string]: string;
}

// api接口 - 此处用了统一保存接口url路径
const api: ApiType = {
    getHeadUrl: '/chat_room_server/get_hall_info', //获取头像列表
    sendCode: "/api/users/send-code",//发送注册验证码
    usersRegister: "/api/users/register", //注册用户
    usersLogin: "/api/users/login",//密码登录
    loginSendCode: "/api/users/login-send-code", //发送登录验证码
    loginCode: "/api/users/login-code",//验证码登录
    resetPasswordCode: "/api/users/reset-password-code", //发送重置密码验证码
    resetPassword: "/api/users/reset-password", //重置密码
    usersMe: "/api/users/me",//认证接口（需要 token）
    usersUpdate: "/api/users/update",//更新用户信息（需要 token）PUT
    guestLogin: "/api/visitors/login",//游客登录
    usersRelationships: "/api/users/relationships", //获取当前用户关系 (好友)
    usersList: "/api/users/list", //获取用户列表
    usersFriendRequests: "/api/users/friend-requests",//获取当前用户 好友申请列表
    updateRelationship: "/api/users/update-relationship", //修改用户关系 PUT
    createRelationship: "/api/users/create-relationship", //添加用户关系 表 post
    usersSearch: "/api/users/search", //搜索用户
    deleteMessages: '/api/messages/delete', // 删除 私聊聊天记录
    visitorStats: "/api/visitor-stats" //获取历史和今日访问
};


for (const key in api) {
    api[key] = `${baseURL}${api[key]}`;
}

export interface VisitorStatsDataType {
    today_visitors: number;
    total_visitors: string
}

//获取历史和今日访问
export function getVisitorStats() {
    return http.get<VisitorStatsDataType>(api.visitorStats)
}

//获取头像列表
export function getHeadUrl(): Promise<Array<string>> {
    return new Promise((resolve, reject) => {
        http.get<get_hall_info_data_type>(api.getHeadUrl).then((res) => {
            resolve(res.data.releaseRole.map((item: number) => `https://nichijou-1300531302.cos.ap-guangzhou.myqcloud.com/avatar/${item}.jpg`));
        }).then(res => {
            reject(res);
        })
    })
}

//发送注册验证码
export function sendCode(email: string): Promise<string> {
    return http.post(api.sendCode, {email: email})
}

//注册用户
export function usersRegister(data: usersRegisterFromType) {
    return http.post<usersRegisterDataType>(api.usersRegister, data)
}

//用户登录
export function usersLogin(email: string, password: string) {
    return http.post<usersLoginDataType>(api.usersLogin, {email: email, password: password})
}

//发送登录验证码
export function loginSendCode(email: string) {
    return http.post(api.loginSendCode, {email: email})
}

//验证码登录
export function loginCode(email: string, verificationCode: string) {
    return http.post<usersLoginDataType>(api.loginCode, {email: email, verificationCode: verificationCode})
}

//发送重置密码验证码
export function resetPasswordCode(email: string) {
    return http.post(api.resetPasswordCode, {email: email})
}

//重置密码
export function resetPassword(email: string, newPassword: string, verificationCode: string) {
    return http.post<usersRegisterDataType>(api.resetPassword, {
        email: email,
        newPassword: newPassword,
        verificationCode: verificationCode
    })
}

//认证接口 获取当前用户信息
export function usersMe(token: string) {
    return http.get<usersLoginDataType>(api.usersMe, {}, {headers: {Authorization: "Bearer " + token}})
}

//更新用户
export function usersUpdate(name: string, gender: string | null, birthdate: string | null, avatar: string, token: string) {
    return http.put<usersLoginDataType>(api.usersUpdate, {
        name: name,
        gender: gender,
        birthdate: birthdate,
        avatar: avatar
    }, {headers: {Authorization: "Bearer " + token}})
}

//游客登录
export function guestLogin(name: string, avatar: string) {
    return http.post<usersLoginDataType>(api.guestLogin, {name: name, avatar: avatar})
}

//当前用户的关系 好友列表
export function usersRelationships() {
    const {token} = getUserInfo()
    return http.get<usersRelationshipsDataDataType>(api.usersRelationships, {}, {headers: {Authorization: "Bearer " + token}})
}

//获取好友申请列表
export function usersFriendRequests() {
    const {token} = getUserInfo()
    return http.get<templateType<Array<usersFriendRequestsDataType>>>(api.usersFriendRequests, {}, {headers: {Authorization: "Bearer " + token}})
}

//获取用户列表
export function usersList(limit: number = 10, offset: number = 0) {
    const {token} = getUserInfo()
    return http.get(api.usersList, {limit, offset}, {headers: {Authorization: "Bearer " + token}})
}


//修改好友关系
export function updateRelationship(userId: number, friendId: number, relationship: string) {
    const {token} = getUserInfo()
    return http.put(api.updateRelationship, {
        userId,
        friendId,
        relationship
    }, {headers: {Authorization: "Bearer " + token}})
}

//添加用户关系
export function createRelationship(userId: number, friendId: number, relationship: string) {
    const {token} = getUserInfo()
    return http.post(api.createRelationship, {
        userId,
        friendId,
        relationship
    }, {headers: {Authorization: "Bearer " + token}})
}

//搜索用户功能
export function usersSearch(keywords: string, limit: number = 10, offset: number = 0) {
    const {token} = getUserInfo()
    return http.get<template<userType[]>>(api.usersSearch, {
        keywords,
        limit,
        offset
    }, {headers: {Authorization: "Bearer " + token}})
}

/// 可选参数，0表示未读，1表示已读，不传则删除所有
export const deleteMessages = (senderId: number, recipientId: number, isRead?: number) => {
    const {token} = getUserInfo()
    return http.post(api.deleteMessages, {senderId, recipientId, isRead}, {headers: {Authorization: "Bearer " + token}})
}